package com.pictureBook.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/1/9 14:59
 */
@CrossOrigin
@RestController
@Api("公共接口")
@RequestMapping("/public")
public class PublicController {

    @Value("${uploadPath}")
    private String upLoadPath;

    @Value("${server.port}")
    private String port;

    @Value("${ipHost}")
    private String ipHost;

    /**
     * 上传用户头像
     * @param file 图片
     * @return JSONObject 新的user对象
     */
    @RequestMapping("/toUpload")
    @ApiOperation("上传图片免压缩")
    @ResponseBody
    public JSONObject toUpload(@RequestParam MultipartFile file) throws UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        //文件夹不存在--创建文件夹
        File file1 = new File(upLoadPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //创建随机文件名
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        //文件后缀
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //新文件名
        String newFileName = filename+ext;
        //新文件全路径
        String url = upLoadPath+newFileName;
        //服务器全称
        String allUrl = ipHost+":"+port+"/"+newFileName;
        try {
            file.transferTo(new File(url));
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonObject.put("stat",200);
        jsonObject.put("url",allUrl);
        return jsonObject;
    }

}
